import javax.persistence.EntityTransaction

const val ANSI_RED = "\u001B[31m"
const val ANSI_GREEN = "\u001B[32m"
const val ANSI_RESET = "\u001B[0m"

fun printlnInRed(message: Any?) = println("$ANSI_RED$message$ANSI_RESET")

fun printlnInGreen(message: Any?) = println("$ANSI_GREEN$message$ANSI_RESET")

inline fun <T> Iterable<T>.forEachSafely(action: (T) -> Unit) {
    for (element in this) {
        try {
            action(element)
        } catch (e: Exception) {
            printlnInRed(e.message)
        }
    }
}

fun EntityTransaction.beginSafely() {
    try {
        this.begin()
        println("transaction began.")
    } catch (e: Exception) {
        printlnInRed("begin transaction failed, because: ${e.message}")
    }
}

fun EntityTransaction.commitSafely() {
    try {
        this.commit()
        println("transaction committed.")
    } catch (e: Exception) {
        printlnInRed("commit transaction failed, because: ${e.message}")
    }
}

fun EntityTransaction.rollbackSafely() {
    try {
        this.rollback()
        println("transaction rollback.")
    } catch (e: Exception) {
        printlnInRed("rollback transaction failed, because: ${e.message}")
    }
}
